package com.spa.infrastructure.service.mp;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.spa.domain.entity.*;
import com.spa.domain.service.OrderService;
import com.spa.domain.service.OrderTransferService;
import com.spa.infrastructure.enums.dict.base.SourceTypeEnum;
import com.spa.infrastructure.repository.condition.OrderTransferCondition;
import com.spa.infrastructure.service.sms.SmsProvider;
import com.spa.infrastructure.service.sms.huaxin.HuaXinUtil;
import com.spa.infrastructure.service.wx.msg.WxMessageService;
import com.spa.infrastructure.service.wx.msg.chat.ChatEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class Producer {

    @Autowired
    private WxMessageService pushWxMessage;

    @Resource
    private OrderService orderService;

    @Resource
    private OrderTransferService orderTransferService;

    @Resource
    private SmsProvider smsProvider;

    @Async
    public void send(FlowEnum flow, Long orderId){
        try {
            if (flow.equals(FlowEnum.$PLACE)) {//下单通知
                sendPlace(orderId);
            } else if (flow.equals(FlowEnum.$CANCEL)) {//取消通知
                sendCancel(orderId);
            } else if (flow.equals(FlowEnum.$TAKE)) {//已接单
                sendTake(orderId);
            } else if (flow.equals(FlowEnum.$COMPLETE)) {//已完成
                sendComplete(orderId);
            } else if (flow.equals(FlowEnum.$DEPART)) {//已出发
                sendDepart(orderId);
            } else if (flow.equals(FlowEnum.$ARRIVE)) {//已到达
                sendArrive(orderId);
            }
        } catch (Exception e) {
            log.error("发送消息失败", e);
        }
    }

    private void sendComplete(Long orderId) {
        OrderInfo orderInfo = getOrderInfo(orderId);
        if (ObjectUtil.isNotNull(orderInfo)) {
            Map<String, String> wxMsg = new HashMap<>();
            String templateId = null;
            if (orderInfo.getSource().equals(SourceTypeEnum.WeChat.getCode())) {
                ChatEnum template = ChatEnum.$MP001;
                templateId = template.getTemplateId();
                Map<String, String> params = template.getParams();
                wxMsg.put(params.get("完成时间"), DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMAT));
                OrderAddress orderClient = orderInfo.getOrderAddress();
                wxMsg.put(params.get("客户姓名"), orderClient.getName());
                wxMsg.put(params.get("服务地址"), orderClient.getAddress());
                wxMsg.put(params.get("服务人员"), orderInfo.getMassagistName());
                OrderTransferCondition condition = new OrderTransferCondition();
                condition.setOrderIds(Lists.newArrayList(orderId));
                condition.setAscCreateTime("asc");//todo
                List<OrderTransfer> orderTransfers = orderTransferService.listByCondition(condition);
                if (CollectionUtil.isNotEmpty(orderTransfers)) {
                    OrderTransfer orderTransfer = orderTransfers.get(0);
                    if (ObjectUtil.isNotNull(orderTransfer)) {
                        wxMsg.put(params.get("服务人员"), orderTransfer.getAppointMassagistName());
                    }
                }
                wxMsg.put(params.get("服务项目"), orderInfo.getServiceName());
            }
            pushWxMessage.send(orderInfo.getSource(), orderInfo.getUserId(), templateId, wxMsg);
        }
    }

    private void sendArrive(Long orderId) {
        OrderInfo orderInfo = getOrderInfo(orderId);
        if (ObjectUtil.isNotNull(orderInfo)) {
            Map<String, String> wxMsg = new HashMap<>();
            String templateId = null;
            if (orderInfo.getSource().equals(SourceTypeEnum.WeChat.getCode())) {
                ChatEnum template = ChatEnum.$MP002;
                templateId = template.getTemplateId();
                Map<String, String> params = template.getParams();
                wxMsg.put(params.get("时间"), DateUtil.format(orderInfo.getArriveTime(), DatePattern.NORM_DATETIME_MINUTE_FORMAT));
                wxMsg.put(params.get("项目名称"), orderInfo.getServiceName());
                wxMsg.put(params.get("技师"), orderInfo.getMassagistName());
                OrderTransferCondition condition = new OrderTransferCondition();
                condition.setOrderIds(Lists.newArrayList(orderId));
                condition.setAscCreateTime("asc");//todo
                List<OrderTransfer> orderTransfers = orderTransferService.listByCondition(condition);
                if (CollectionUtil.isNotEmpty(orderTransfers)) {
                    OrderTransfer orderTransfer = orderTransfers.get(0);
                    if (ObjectUtil.isNotNull(orderTransfer)) {
                        wxMsg.put(params.get("技师"), orderTransfer.getAppointMassagistName());
                    }
                }
            }
            pushWxMessage.send(orderInfo.getSource(), orderInfo.getUserId(), templateId, wxMsg);
        }
    }

    private void sendDepart(Long orderId) {
        OrderInfo orderInfo = getOrderInfo(orderId);
        if (ObjectUtil.isNotNull(orderInfo)) {
            Map<String, String> wxMsg = new HashMap<>();
            String templateId = null;
            if (orderInfo.getSource().equals(SourceTypeEnum.WeChat.getCode())) {
                ChatEnum template = ChatEnum.$MP0031;
                templateId = template.getTemplateId();
                Map<String, String> params = template.getParams();
                wxMsg.put(params.get("出发时间"), DateUtil.format(orderInfo.getDepartTime(), DatePattern.NORM_DATETIME_FORMAT));
                OrderAddress orderClient = orderInfo.getOrderAddress();
                wxMsg.put(params.get("服务地址"), orderClient.getAddress());
                wxMsg.put(params.get("技师"), orderInfo.getMassagistName());
                OrderTransferCondition condition = new OrderTransferCondition();
                condition.setOrderIds(Lists.newArrayList(orderId));
                condition.setAscCreateTime("asc");//todo
                List<OrderTransfer> orderTransfers = orderTransferService.listByCondition(condition);
                if (CollectionUtil.isNotEmpty(orderTransfers)) {
                    OrderTransfer orderTransfer = orderTransfers.get(0);
                    if (ObjectUtil.isNotNull(orderTransfer)) {
                        wxMsg.put(params.get("技师"), orderTransfer.getAppointMassagistName());
                    }
                }
            }
            pushWxMessage.send(orderInfo.getSource(), orderInfo.getUserId(), templateId, wxMsg);
        }
    }

    private void sendTake(Long orderId) {
        OrderInfo orderInfo = getOrderInfo(orderId);
        if (ObjectUtil.isNotNull(orderInfo)) {
            Map<String, String> wxMsg = new HashMap<>();
            String templateId = null;
            if (orderInfo.getSource().equals(SourceTypeEnum.WeChat.getCode())) {
                ChatEnum template = ChatEnum.$MP004;
                templateId = template.getTemplateId();
                Map<String, String> params = template.getParams();
                wxMsg.put(params.get("预约时间"), DateUtil.format(orderInfo.getAppointTime(), DatePattern.NORM_DATETIME_MINUTE_FORMAT));
                OrderAddress orderClient = orderInfo.getOrderAddress();
                wxMsg.put(params.get("服务地址"), orderClient.getAddress());
                wxMsg.put(params.get("技师姓名"), orderInfo.getMassagistName());
                OrderTransferCondition condition = new OrderTransferCondition();
                condition.setOrderIds(Lists.newArrayList(orderId));
                condition.setAscCreateTime("asc");//todo
                List<OrderTransfer> orderTransfers = orderTransferService.listByCondition(condition);
                if (CollectionUtil.isNotEmpty(orderTransfers)) {
                    OrderTransfer orderTransfer = orderTransfers.get(0);
                    if (ObjectUtil.isNotNull(orderTransfer)) {
                        wxMsg.put(params.get("技师姓名"), orderTransfer.getAppointMassagistName());
                    }
                }
                wxMsg.put(params.get("服务项目"), orderInfo.getServiceName());
            }
            pushWxMessage.send(orderInfo.getSource(), orderInfo.getUserId(), templateId, wxMsg);
        }
    }

    private void sendCancel(Long orderId) {
        OrderInfo orderInfo = getOrderInfo(orderId);
        if (ObjectUtil.isNotNull(orderInfo)) {
            Map<String, String> wxMsg = new HashMap<>();
            ChatEnum template = ChatEnum.$MP005;
            String templateId = template.getTemplateId();
            Map<String, String> params = template.getParams();
            wxMsg.put(params.get("预约时间"), DateUtil.format(orderInfo.getAppointTime(), DatePattern.NORM_DATETIME_MINUTE_FORMAT));
            wxMsg.put(params.get("取消原因"), orderInfo.getCancelReason());
            OrderAddress orderClient = orderInfo.getOrderAddress();
            wxMsg.put(params.get("客户名称"), orderClient.getName());
            wxMsg.put(params.get("预约技师"), orderInfo.getMassagistName());
            OrderTransferCondition condition = new OrderTransferCondition();
            condition.setOrderIds(Lists.newArrayList(orderId));
            condition.setAscCreateTime("asc");//todo
            List<OrderTransfer> orderTransfers = orderTransferService.listByCondition(condition);
            if (CollectionUtil.isNotEmpty(orderTransfers)) {
                OrderTransfer orderTransfer = orderTransfers.get(0);
                if (ObjectUtil.isNotNull(orderTransfer)) {
                    wxMsg.put(params.get("预约技师"), orderTransfer.getAppointMassagistName());
                }
            }
            pushWxMessage.send(SourceTypeEnum.WeChat.getCode(), orderInfo.getMassagistId(), templateId, wxMsg);
        }
    }

    private void sendPlace(Long orderId) {
        OrderInfo orderInfo = getOrderInfo(orderId);
        if (ObjectUtil.isNotNull(orderInfo)) {
            Map<String, String> wxMsg = new HashMap<>();
            ChatEnum template = ChatEnum.$MP006;
            String templateId = template.getTemplateId();
            Map<String, String> params = template.getParams();
            wxMsg.put(params.get("服务时间"), DateUtil.format(orderInfo.getAppointTime(), DatePattern.NORM_DATETIME_MINUTE_FORMAT));
            OrderAddress orderClient = orderInfo.getOrderAddress();
            wxMsg.put(params.get("客户姓名"), orderClient.getName());
            String phoneNumber = orderClient.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
            wxMsg.put(params.get("客户电话"), phoneNumber);
            wxMsg.put(params.get("服务地址"), orderClient.getAddress());
            smsProvider.sendNotice(orderInfo.getMassagistPhone(), HuaXinUtil.template2(orderInfo.getOrderCode()));
            pushWxMessage.send(SourceTypeEnum.WeChat.getCode(), orderInfo.getMassagistId(), templateId, wxMsg);
        }
    }

    private OrderInfo getOrderInfo(Long orderId) {
        return orderService.getOrderInfoById(orderId, OrderService.OrderInfoPlug.empty());
    }
}
